<?php

namespace App\Admin\Forms\Withdrawal;

use App\Exceptions\AdminInvalidRequestException;
use App\Jobs\OrderJob;
use App\Jobs\WithdrawalJob;
use App\Models\Order;
use App\Models\PaymentAddress;
use App\Models\PaymentThirdPay;
use App\Models\User;
use Carbon\Carbon;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Godruoyi\Snowflake\Snowflake;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class AuditForm extends Form implements LazyRenderable
{
    use LazyWidget;

    private int $expire = 30;
    private int $state;
    private string $remark;
    private string $key;
    private  $payment;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return JsonResponse
     * @throws AdminInvalidRequestException
     */
    public function handle(array $input): JsonResponse
    {
        $ids = explode(',', $input['ids'] ?? null);
        if (!$ids) {
            throw new AdminInvalidRequestException(trans('error.400'));
        }

        $this->state = $input['states'];
        //$this->key = $input['key'] ?? '';
        $this->remark = $input['remark'] ?? '';
        $payment_address_id = $input['payment_address_id'] ?? 0;
        if ($this->state == Order::PENDING && !$payment_address_id) {
            throw new AdminInvalidRequestException('请选择出款账户');
        }
        //$this->payment_address = PaymentAddress::where('id', '=', $payment_address_id)->first();
        $this->payment = PaymentThirdPay::where('id','=',$payment_address_id)->first();

        foreach ($ids as $id) {
            Cache::lock(sprintf('audit:%d', $id), $this->expire)->get(function () use ($id) {
                DB::transaction(function () use ($id) {
                    $order = Order::where('id', '=', $id)->lockForUpdate()->first();
                    if ($order->state == Order::REVIEW) {
                        switch ($this->state) {
                            case Order::PENDING:
                                $re = $this->approve($order);
                                if($re === 1){
                                    throw new AdminInvalidRequestException('超出出款账号上下限额');
                                }
                                break;
                            case Order::REFUSE:
                                $this->refuseOrCancel($order, 'refuse');
                                break;
                            case Order::CANCEL:
                                $this->refuseOrCancel($order, 'cancel');
                                break;
                            case Order::SUCCESS:
                                (new Order())->withdrawComplete([
                                    'state' => Order::SUCCESS,
                                    'orderId' => $order->no,
                                    'paidAt' => Carbon::now()->timestamp
                                ], ['mag' => '后台操做']);
                                break;
                        }
                    }

                });
            });
        }
        return $this
            ->response()
            ->success(trans('admin.succeeded'))
            ->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {

        $this->radio('states', trans('order.fields.state'))->options([
            Order::PENDING => '通过',
            Order::REFUSE => '拒绝',
            Order::CANCEL => '取消',
            Order::SUCCESS => '成功',
        ])
            ->when(Order::PENDING, function (Form $form) {
                $form->select('payment_address_id', trans('payment-address.labels.PaymentAddress'))->options(
                    PaymentThirdPay::query()
                        ->open()
                        ->withdrawal(PaymentThirdPay::WITHDRAWAL_OPEN)
                        ->pluck('title','id')->toArray()
                );
            })
            ->required();
        $this->text('remark', trans('order.fields.remark'));
        $this->hidden('ids')->attribute('id', 'batch-ids');
    }


    //同意
    private function approve(Order $order)
    {
        $attach = [];

        if ($order->payment_no) {
            $order->no = (new Snowflake())->id();
            $order->payment_no = '';
            $order->paid_at = '';
            $order->closed = 0;
        }
        if (!$order->platform) {
            $order->platform = $this->payment->server_name;
            $order->payment_third_pay_id = $this->payment->id;
        }


        //$order->platform = $this->payment->address;
        //$order->payment_third_pay_id = $this->payment->id;
        $order->remark = $this->remark;
        $order->state = $this->state;
        $order->save();
        //$attach['key'] = $this->payment_address->key . $this->key;//秘钥拼接
        //WithdrawalJob::dispatch($order, $attach)->onQueue(env('REDIS_QUEUE', 'default'));
        OrderJob::dispatch($order,[])->onQueue(config('jobQueue.default'))->delay(now()->addSeconds(5));
        return 0;
    }


    public function refuseOrCancel(Order $order, string $type)
    {
        if ($type == 'refuse') {
            User::where('id', '=', $order->user_id)->decrement('freeze_balance', $order->amount);
        } else {
            Order::returnUserMoney($order);
        }
        $order->state = $this->state;
        $order->remark = $this->remark;
        $order->closed = 1;
        $order->save();
    }


}
